import React, { useState, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { supportedLanguages } from '../i18n/i18n';
import { getDynamicFonts } from '@/utils/fontUtils';

// import ''; // 导入字体样式文件
interface LanguageSelectorProps {
  className?: string;
  buttonRef?: React.Ref<HTMLDivElement>;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
  jx?: boolean; // 新增：是否显示简写
  onLanguageChange?: () => void; // 新增：语言切换后的回调
}

// 检查是否为开发环境
const isDevelopment = import.meta.env.DEV || import.meta.env.MODE === 'development';

// 定义全局动画样式
const fadeInAnimation = `
  @keyframes langFadeIn {
    from {
      opacity: 0;
      transform: translateY(-10px) scale(0.95);
    }
    to {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }
`;

// 添加样式到文档头部
if (typeof document !== 'undefined') {
  const styleEl = document.createElement('style');
  styleEl.appendChild(document.createTextNode(fadeInAnimation));
  document.head.appendChild(styleEl);
}

const LanguageSelector: React.FC<LanguageSelectorProps> = ({ className = '', buttonRef, open, onOpenChange, jx, onLanguageChange }) => {
  const { i18n, t } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);
  const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
  const isControlled = typeof open === 'boolean' && typeof onOpenChange === 'function';
  const isOpen = isControlled ? open : uncontrolledOpen;
  const setIsOpen = (v: boolean) => {
    if (isControlled) {
      onOpenChange?.(v);
      // console.log('isControlled', isOpen);
    } else {
      setUncontrolledOpen(v);
    }
  };
  const dropdownRef = useRef<HTMLDivElement>(null);

  // 获取当前语言 - 确保在生产环境下不显示中文
  const getCurrentLanguage = () => {
    const currentLang = supportedLanguages.find(lang => lang.code === i18n.language);
    if (currentLang) {
      return currentLang;
    }
    // 如果当前语言不在支持列表中（比如生产环境下的中文），返回日文
    return supportedLanguages.find(lang => lang.code === 'ja') || supportedLanguages[0];
  };

  const currentLanguage = getCurrentLanguage();

  // 语言代码到国旗emoji的映射
  const flagEmoji: Record<string, string> = {
    'zh': '🇨🇳',
    'en': '🇺🇸',
    'ja': '🇯🇵'
  };

  // 语言代码到简写的映射
  const langAbbr: Record<string, string> = {
    'zh': '中文',
    'en': 'English',
    'ja': '日本語'
  };

  // 切换语言
  const changeLanguage = (code: string) => {
    // 在生产环境下，禁止切换到中文和英文
    if (!isDevelopment && (code === 'zh' || code === 'en')) {
      console.warn(`${code === 'zh' ? 'Chinese' : 'English'} language is not available in production environment`);
      return;
    }

    // 检查语言是否在支持列表中
    const isSupported = supportedLanguages.some(lang => lang.code === code);
    if (!isSupported) {
      console.warn(`Language ${code} is not supported in current environment`);
      return;
    }

    i18n.changeLanguage(code);
    setIsOpen(false);
    // 保存语言选择到本地存储
    localStorage.setItem('i18nextLng', code);
    // 如果有回调函数，执行回调（用于关闭侧边栏等）
    onLanguageChange?.();
  };

  // 检查当前环境和语言状态
  useEffect(() => {
    if (!isDevelopment && (i18n.language === 'zh' || i18n.language === 'en')) {
      // 在生产环境下，如果当前语言是中文或英文，自动切换到日文
      // console.log('Production environment: Switching from Chinese/English to Japanese');
      changeLanguage('ja');
    }
  }, [i18n.language, isDevelopment]);

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isControlled, onOpenChange]);

  return (
    <div style={{ fontFamily: dynamicFonts.font2 }} className={`relative ${className}`} ref={dropdownRef}>
      {/* 语言选择按钮 */}
      <div
        ref={buttonRef}
        onClick={() => setIsOpen(!isOpen)}
        style={{ fontFamily: dynamicFonts.font2, width: "100%" }}
        className={`flex justify-between items-center text-[rgb(209,209,209)] hover:text-white transition-colors cursor-pointer ${i18n.language === 'en' ? 'font-ENnFont' : i18n.language === 'zh' ? 'font-CNFont' : i18n.language === 'ja' ? 'font-JPFont' : ''}`}
        aria-label={t('common.language')}
      >
        <div >
          <span className="text-[0.8rem] mr-1">{flagEmoji[currentLanguage.code]}</span>
          <span style={{ fontFamily: dynamicFonts.font3 }} className='text-[0.8rem]'>
            {jx ? langAbbr[currentLanguage.code] : currentLanguage.name}
          </span>
        </div>
        {/* 新增：展开和收起icon  */}
        <span className="ml-2 flex items-center">
          <i className={`fas ${isOpen ? 'fa-chevron-up' : 'fa-chevron-down'} text-xs text-gray-400`}></i>
        </span>
      </div>

      {/* 下拉菜单 */}
      {isOpen && (
        <div
          className="absolute left-0 bottom-full mb-2 w-full min-w-[110px] sm:min-w-[148px] rounded-md shadow-lg bg-[#1e1e1e] border border-gray-600 z-50 overflow-auto max-h-80"
          style={{
            animation: 'langFadeIn 0.2s ease-out forwards',
            transformOrigin: 'bottom left',
            fontFamily: dynamicFonts.font2,
          }}
        >
          {/* 语言选项 */}
          <div className="py-1 cursor-pointer ">
            {supportedLanguages
              .filter(lang => isDevelopment || (lang.code !== 'zh' && lang.code !== 'en'))
              .map((lang) => (
                <div
                  key={lang.code}
                  onClick={() => changeLanguage(lang.code)}
                  className={`flex items-center w-full px-3 py-2 text-[0.8rem] text-left transition-colors ${lang.code === i18n.language
                    ? 'text-white'
                    : 'text-gray-300 hover:text-white'
                    }`}
                >
                  <span className="text-base mr-2">{flagEmoji[lang.code]}</span>
                  <span className="truncate">{jx ? langAbbr[lang.code] : lang.name}</span>
                  {lang.code === i18n.language && (
                    <span className="ml-auto text-blue-400">
                      <i className="fas fa-check"></i>
                    </span>
                  )}
                </div>
              ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default LanguageSelector; 